<script setup>
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { message } from 'ant-design-vue'
const emit = defineEmits(['change'])
const props = defineProps({
  val: {
    type: String,
    default: '',
  },
})
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const html = ref(props.val)
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    fullScreen: {
      title: '全屏',
      enable: false,
    },
    // 配置上传图片
    uploadImage: {
      server: '/api/api/common/file',
      fieldName: 'file',
      customInsert(res, insertFn) {
        console.log(res)
        const { code, data, message } = res
        if (code === 0) {
          const { download_url } = data
          insertFn(download_url)
        } else {
          message.error(message)
        }
      },
    },
    // 配置上传视频
    uploadVideo: {
      server: '/api/api/common/file',
      fieldName: 'file',
      customInsert(res, insertFn) {
        console.log(res)
        const { code, data, message } = res
        if (code === 0) {
          const { download_url } = data
          insertFn(download_url)
        } else {
          message.error(message)
        }
      },
    },
  },
}

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) editorRef.value.destroy()
})
</script>
<template>
  <a-card class="max-w-[1000px]">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
    />
    <Editor
      style="height: 500px"
      v-model="html"
      :defaultConfig="editorConfig"
      @onCreated="handleCreated"
      @onChange="emit('change', html)"
    />
  </a-card>
</template>

<style>
.w-e-full-screen-container {
  z-index: 999 !important;
}
</style>
